<template>
    <el-dialog
        title="请选择车辆存放地点"
        :close-on-click-modal="false"
        :visible.sync="showDialog"
        lock-scroll
        width="74%"
        :before-close="closeForm"
    >
        <el-row :gutter="15">
            <el-col :span="8">
                <el-form
                    ref="locationForm"
                    :model="dataForm"
                    :rules="rules"
                    size="small"
                    label-width="70px"
                    label-position="top"
                >
                    <el-col :span="24">
                        <el-form-item label="存放车辆" prop="kqLongitude">
                            <el-input
                                v-model="carNo"
                                placeholder="自动带出"
                                :style="{ width: '100%' }"
                                disabled
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="地点" prop="address">
                            <el-input
                                type="textarea"
                                v-model="dataForm.address"
                                placeholder="选择地图上的位置自动带出,可编辑"
                                clearable
                                :style="{ width: '100%' }"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="经度" prop="kqLongitude">
                            <el-input
                                v-model="dataForm.kqLongitude"
                                placeholder="选择地图上的位置自动带出"
                                :style="{ width: '100%' }"
                                disabled
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="纬度" prop="kqLatitude">
                            <el-input
                                v-model="dataForm.kqLatitude"
                                placeholder="选择地图上的位置自动带出"
                                :style="{ width: '100%' }"
                                disabled
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-col>
            <el-col :span="16">
                <div style="width: 100%">
                    <div class="amap_search_box">
                        <div class="label">关键字搜索</div>
                        <el-input
                            v-model="input"
                            placeholder="请输入关键字搜索"
                            id="tipinput"
                        ></el-input>
                    </div>
                    <div ref="gaode_Map" id="gaode_Map"></div>
                </div>
            </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeForm">取 消</el-button>
            <el-button type="primary" @click="dataFormSubmit()"
                >确 定</el-button
            >
        </span>
    </el-dialog>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader"; //amapSecretKey

export default {
    components: {},
    props: ["carNo"],
    data() {
        return {
            showDialog: false,
            dataForm: {
                kqLocation: undefined,
                kqLongitude: undefined,
                kqLatitude: undefined,
                address: "",
            },
            rules: {
                address: [
                    {
                        required: true,
                        message: "地点不能为空",
                        trigger: "change",
                    },
                ],
                kqLongitude: [
                    {
                        required: true,
                        message: "经度不能为空",
                        trigger: "change",
                    },
                ],
                kqLatitude: [
                    {
                        required: true,
                        message: "纬度不能为空",
                        trigger: "change",
                    },
                ],
            },
            input: "",
            map: null,
            auto: null,
            placeSearch: null,
            lnglat: [],
            markers: [],
            position: {},
            citysearch: null,
            geoLoc: null,
            cityCode: "",
        };
    },
    computed: {},

    created() {
      window._AMapSecurityConfig = {
        // 设置安全密钥
        securityJsCode: this.$store.state.user.amapSecretKey
      };
    },
    mounted() {


    },
    methods: {
        show(cityName) {
            this.showDialog = true;
            this.initMap(cityName);
        },
        // 地图初始化
        initMap(cityName) {
            AMapLoader.load({
                key: this.$store.state.user.amapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [
                    "AMap.AutoComplete",
                    "AMap.PlaceSearch",
                    "AMap.Geocoder",
                    "AMap.Geolocation",
                    "AMap.CitySearch",
                ],
            })
                .then((AMap) => {
                    let centerLen = null;
                    const geocoder = new AMap.Geocoder({
                        city: "全国", // 逆地理编码时，以给定城市为优先
                        batch: false, // 批量查询
                    });
                    geocoder.getLocation(cityName, function (status, result) {
                        if (status === "complete" && result.info === "OK") {
                            // result为对应的地理编码信息和行政区信息
                            const { geocodes } = result;
                            const lnglat = geocodes[0].location;
                            centerLen = [lnglat.lng, lnglat.lat];
                        }
                    });
                    this.map = new AMap.Map("gaode_Map", {
                        // 设置地图容器id
                        viewMode: "3D", //  是否为3D地图模式
                        zoom: 11, // 初始化地图级别
                        center: centerLen, //中心点坐标
                        resizeEnable: true,
                    });

                    // 浏览器城市定位
                    this.getCityLocation();
                    // 设置中心点
                    // this.setMarker(centerLen);
                    // 监听鼠标点击事件
                    this.map.on("click", this.clickMapHandler);
                })
                .catch((e) => {});
        },
        // 关键字查询
        searchMap() {
            // 搜索框自动完成类
            this.auto = new AMap.AutoComplete({
                city: this.cityCode,
                input: "tipinput", // 使用联想输入的input的id
            });
            //构造地点查询类
            this.placeSearch = new AMap.PlaceSearch({
                map: this.map,
            });
            // 当选中某条搜索记录时触发
            this.auto.on("select", this.selectSite);
        },
        //选中查询出的记录
        selectSite(e) {
            if (e.poi.location) {
                this.lnglat = [e.poi.location.lng, e.poi.location.lat];
                this.$set(this.dataForm, "kqLongitude", e.poi.location.lng);
                this.$set(this.dataForm, "kqLatitude", e.poi.location.lat);
                this.$set(
                    this.dataForm,
                    "kqLocation",
                    e.poi.location.lng + "," + e.poi.location.lat
                ); //纬度，经度
                this.placeSearch.setCity(e.poi.adcode);
                this.placeSearch.search(e.poi.name); //关键字查询
                this.placeSearch.on("markerClick", this.markerClick);
                let geocoder = new AMap.Geocoder({});
                geocoder.getAddress(this.lnglat, (status, result) => {
                    if (status === "complete" && result.regeocode) {
                        this.regeoAddress(result);
                    }
                });
            } else {
                this.$message.error("查询地址失败，请重新输入地址");
            }
        },
        // 点击地图事件获取经纬度，并添加标记
        clickMapHandler(e) {
            this.dataForm.kqLongitude = e.lnglat.getLng();
            this.dataForm.kqLatitude = e.lnglat.getLat();
            this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
            this.setMarker(this.lnglat);
            // 点击地图上的位置，根据经纬度转换成详细地址
            let geocoder = new AMap.Geocoder({});
            let that = this;
            geocoder.getAddress(this.lnglat, (status, result) => {
                if (status === "complete" && result.regeocode) {
                    this.regeoAddress(result);
                }
            });
            this.position = {
                longitude: e.lnglat.getLng(),
                latitude: e.lnglat.getLat(),
                address: that.address,
            };
            this.input = that.address; //把查询到的地址赋值到输入框
        },
        //  添加标记
        setMarker(lnglat) {
            this.removeMarker();
            let marker = new AMap.Marker({
                position: lnglat,
            });
            marker.setMap(this.map);
            this.markers.push(marker);
        },
        // 删除之前后的标记点
        removeMarker() {
            if (this.markers) {
                this.map.remove(this.markers);
            }
        },
        closeForm() {
            this.showDialog = false;
        },
        dataFormSubmit() {
            this.$refs["locationForm"].validate((valid) => {
                if (valid) {
                    this.$emit("chooseLocationSuccess", this.dataForm);
                    this.closeForm();
                }
            });
        },
        regeoAddress(result) {
            let {
                formattedAddress,
                addressComponent: { township },
            } = result.regeocode;
            console.log("位置信息---", formattedAddress);
            // let indexStr = formattedAddress.indexOf(township) + township.length;
            // let address = formattedAddress;
            // if (indexStr != -1) {
            //   address = address.substring(indexStr);
            // }
            this.$set(this.dataForm, "address", formattedAddress);
        },
        // 点击搜索出来的poi点标记
        markerClick(e) {
            console.log("poi", e);
            this.dataForm.address = e.data.name;
            this.dataForm.kqLatitude = e.data.location.lat;
            this.dataForm.kqLongitude = e.data.location.lng;
        },
        getCityLocation() {
            this.citysearch = new AMap.CitySearch();
            this.citysearch.getLocalCity((status, result) => {
                if (status === "complete" && result.info === "OK") {
                    if (result && result.city && result.bounds) {
                        this.cityCode = result.adcode;
                        // 关键字查询
                        this.searchMap();
                    }
                }
            });
        },
    },
};
</script>

<style lang="scss">
.amap_search_box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 50px;

    .label {
        color: #000;
        width: 100px;
    }
}



#panel {
    position: absolute;
    top: 50px;
    right: 20px;
}

#gaode_Map {
    overflow: hidden;
    width: 100%;
    height: 540px;
    margin: 0;
}

.amap-sug-result {
    z-index: 999999;
}
</style>
